﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Hammock;
using Hammock.Authentication.OAuth;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Practices.Prism.Events;
using ShakeGestures;
using WeiboPlus.Common;
using WeiboPlus.Models;
using WeiboPlus.Service;
using WeiboPlus.Service.Event;
using WeiboPlus.Shell.ViewModel;
using WeiboPlus.Sina;
using Coding4Fun.Phone.Controls;
using System.Windows.Threading;
using System.Threading;
using WeiboPlus.Shell.Model;

namespace WeiboPlus.Shell.Views
{
    public partial class MainView : PhoneApplicationPage
    {
        private bool hasInit = false;
        MainViewModel _mainViewModel;
        private IEventAggregator _ev;


        //ScrollViewer svSearch;

        public MainView()
        {
            InitializeComponent();

            _mainViewModel = new MainViewModel();

            this.DataContext = _mainViewModel;

            Loaded += (s, e) =>
            {
                if (hasInit)
                    return;
                hasInit = true;

                if (_mainViewModel.HasBindedAccount)
                {
                    label.Text = "        " + @"欢迎和我们一起踏上神奇的塔罗牌之旅，塔罗牌拥有神奇的力量，只要你愿意相信，这种力量就会显现出来，无论你原来是否相信，从这一刻起，请跟紧塔罗牌的脚步，在充满魔力的世界里，探寻你心中想要的真！" + Environment.NewLine + Environment.NewLine + @"        在开始洗牌之前，请在心中默念你要问的问题，然后请按洗牌。";
                }

                _ev = PhoneApplicationController.Current.Container.Resolve<IEventAggregator>();
                _ev.GetEvent<NavigationRequestEvent>().Subscribe(HandlleNavigateRequest);
          
            };
        }

        public void HandlleNavigateRequest(NavigationContext context)
        {
            var accountID = context.SimpleParameter.ToString();
            if (string.IsNullOrEmpty(accountID) || context.Destination == null)
            {
                return;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                NavigationService.Navigate(new Uri("/Views/AuthPage.xaml?accountid=" + accountID, UriKind.RelativeOrAbsolute));
            }
            );
        }

        void Current_Deactivated(object sender, DeactivatedEventArgs e)
        {

        }

        void reviewItem_Click(object sender, EventArgs e)
        {
            MarketplaceReviewTask t = new MarketplaceReviewTask();
            t.Show();
            //NavigationService.Navigate(new Uri("/Views/SearchView.xaml", UriKind.RelativeOrAbsolute));
            //throw new NotImplementedException();
        }

        void share_Click(object sender, EventArgs e)
        {
            _mainViewModel.ClearPhoto.Execute();
            //throw new NotImplementedException();
        }

        void sendStatus_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(tbSend.Text))
            //{
            //    return;
            //}
            //_mainViewModel.StatusToUpdate = tbSend.Text;
            //_mainViewModel.Send.Execute();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //base.OnNavigatedTo(e);
            //ContentGrid.ItemsSource = _mainViewModel.Items;
            var count = NavigationService.BackStack.Count();
            for (int i = 0; i <
                count; i++)
            {
                if (NavigationService.CanGoBack)
                    NavigationService.RemoveBackEntry();
            }
        }

        Card choosedCard;
        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Random r = new Random(DateTime.Now.Second);
            var selectedImage = sender as Image;

            choosedCard = _mainViewModel.GetCard(r.Next(21));

            bool isOpposite = r.Next(0, 2) == 1;

            var choosedImage = new Image
            {
                Height = 280,
                Width = 160,
                Source = new BitmapImage
                {
                    UriSource =new Uri(choosedCard.Imagesource,UriKind.Relative)
                },
                Clip = new RectangleGeometry
                {
                    RadiusX = 16,
                    RadiusY = 16,
                    Rect = new Rect(0, 0, 160, 280)
                }
            };
            choosedImage.SetValue(Canvas.TopProperty, 60.0);
            choosedImage.SetValue(Canvas.LeftProperty, 160.0);
            

            if (selectedImage != null)
            {
                List<Image> imagesToRemove = new List<Image>();
                foreach (var c in canvas.Children)
                {
                    var image = c as Image;
                    if (image != null && !image.Equals(selectedImage))
                    {
                        imagesToRemove.Add(image);
                    }
                }

                foreach (var image in imagesToRemove)
                {
                    canvas.Children.Remove(image);
                }

                var left = (double)selectedImage.GetValue(Canvas.LeftProperty);
                var top = (double)selectedImage.GetValue(Canvas.TopProperty);

                Storyboard sb = new Storyboard();
                DoubleAnimationUsingKeyFrames daLeft = new DoubleAnimationUsingKeyFrames()
                {
                    AutoReverse = false,
                    BeginTime = TimeSpan.FromMilliseconds(500)
                };
                EasingDoubleKeyFrame kf1 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                    Value = left,
                };
                EasingDoubleKeyFrame kf2 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1000)),
                    Value = 160,
                };
                daLeft.KeyFrames.Add(kf1);
                daLeft.KeyFrames.Add(kf2);
                Storyboard.SetTarget(daLeft, selectedImage);
                Storyboard.SetTargetProperty(daLeft, new PropertyPath("(Canvas.Left)"));

                DoubleAnimationUsingKeyFrames daTop = new DoubleAnimationUsingKeyFrames()
                {
                    AutoReverse = false,
                    BeginTime = TimeSpan.FromMilliseconds(500)
                };
                EasingDoubleKeyFrame kf3 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                    Value = top,
                };
                EasingDoubleKeyFrame kf4 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1000)),
                    Value = 60,
                };
                daTop.KeyFrames.Add(kf3);
                daTop.KeyFrames.Add(kf4);
                Storyboard.SetTarget(daTop, selectedImage);
                Storyboard.SetTargetProperty(daTop, new PropertyPath("(Canvas.Top)"));

                DoubleAnimationUsingKeyFrames rotation = new DoubleAnimationUsingKeyFrames()
                {
                    AutoReverse = false,
                    BeginTime = TimeSpan.FromMilliseconds(1500)
                };
                EasingDoubleKeyFrame kf5 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                    Value = 0,
                };
                EasingDoubleKeyFrame kf6 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(500)),
                    Value = 90,
                };
                rotation.KeyFrames.Add(kf5);
                rotation.KeyFrames.Add(kf6);
                selectedImage.Projection = new PlaneProjection();
                Storyboard.SetTarget(rotation, selectedImage);
                Storyboard.SetTargetProperty(rotation, new PropertyPath("(UIElement.Projection).(PlaneProjection.RotationY)"));

                //rotate choosed image
                canvas.Children.Add(choosedImage);

                DoubleAnimationUsingKeyFrames rotation2 = new DoubleAnimationUsingKeyFrames()
                {
                    AutoReverse = false,
                    BeginTime = TimeSpan.FromMilliseconds(0)
                };
                EasingDoubleKeyFrame kf7 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                    Value = -90,
                };
                EasingDoubleKeyFrame kf8 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(2000)),
                    Value = -90,
                };
                EasingDoubleKeyFrame kf9 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(2500)),
                    Value = 0,
                };
                rotation2.KeyFrames.Add(kf7);
                rotation2.KeyFrames.Add(kf8);
                rotation2.KeyFrames.Add(kf9);
                choosedImage.Projection = new PlaneProjection();
                Storyboard.SetTarget(rotation2, choosedImage);
                Storyboard.SetTargetProperty(rotation2, new PropertyPath("(UIElement.Projection).(PlaneProjection.RotationY)"));
                sb.Children.Add(rotation2);

                if (isOpposite)
                {
                    DoubleAnimationUsingKeyFrames rotation3 = new DoubleAnimationUsingKeyFrames()
                    {
                        AutoReverse = false,
                        BeginTime = TimeSpan.FromMilliseconds(0)
                    };
                    EasingDoubleKeyFrame kf16 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                        Value = 180,
                    };
                    rotation3.KeyFrames.Add(kf16);
                    Storyboard.SetTarget(rotation3, choosedImage);
                    Storyboard.SetTargetProperty(rotation3, new PropertyPath("(UIElement.Projection).(PlaneProjection.RotationZ)"));
                    sb.Children.Add(rotation3);
                }
                //scan the choosed image
                DoubleAnimationUsingKeyFrames scanx = new DoubleAnimationUsingKeyFrames()
                {
                    AutoReverse = false,
                    BeginTime = TimeSpan.FromMilliseconds(2000)
                };
                EasingDoubleKeyFrame kf10 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                    Value = 1,
                };
                EasingDoubleKeyFrame kf11 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(600)),
                    Value = 1.5,
                };
                scanx.KeyFrames.Add(kf10);
                scanx.KeyFrames.Add(kf11);
                choosedImage.RenderTransform = new ScaleTransform();
                Storyboard.SetTarget(scanx, choosedImage);
                Storyboard.SetTargetProperty(scanx, new PropertyPath("(UIElement.RenderTransform).(ScaleTransform.ScaleX)"));
                sb.Children.Add(scanx);

                DoubleAnimationUsingKeyFrames scany = new DoubleAnimationUsingKeyFrames()
                {
                    AutoReverse = false,
                    BeginTime = TimeSpan.FromMilliseconds(2000)
                };
                EasingDoubleKeyFrame kf12 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                    Value = 1,
                };
                EasingDoubleKeyFrame kf13 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(600)),
                    Value = 1.5,
                };
                scany.KeyFrames.Add(kf12);
                scany.KeyFrames.Add(kf13);
                Storyboard.SetTarget(scany, choosedImage);
                Storyboard.SetTargetProperty(scany, new PropertyPath("(UIElement.RenderTransform).(ScaleTransform.ScaleY)"));
                sb.Children.Add(scany);

                //adjust left
                DoubleAnimationUsingKeyFrames adjustleft = new DoubleAnimationUsingKeyFrames()
                {
                    AutoReverse = false,
                    BeginTime = TimeSpan.FromMilliseconds(2000)
                };
                EasingDoubleKeyFrame kf14 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                    Value = 160,
                };
                EasingDoubleKeyFrame kf15 = new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(600)),
                    Value = 120,
                };
                adjustleft.KeyFrames.Add(kf14);
                adjustleft.KeyFrames.Add(kf15);
                Storyboard.SetTarget(adjustleft, choosedImage);
                Storyboard.SetTargetProperty(adjustleft, new PropertyPath("(Canvas.Left)"));
                sb.Children.Add(adjustleft);

                sb.Children.Add(daLeft);
                sb.Children.Add(daTop);
                sb.Children.Add(rotation);
                sb.Begin();

                ThreadPool.QueueUserWorkItem((o) =>
                {
                    Thread.Sleep(3000);
                    Dispatcher.BeginInvoke(() =>
                    {
                        label.FontSize = 28;
                        label.SetValue(FrameworkElement.MarginProperty,new Thickness(40,10,40,40));
                        label.Text = choosedCard.Title+" "+(isOpposite? " 逆位": " 正位");
                        btnShuffle.Content = "解牌";
                        btnShuffle.IsEnabled = true;
                    });
                }, null);
            }
        }

        bool isShuffled;//是否完成洗牌
        bool isCuted;//是否完成切牌
        bool isDrawed;//是否完成抽牌

        DispatcherTimer timer;
        private void btnShuffle_Click(object sender, RoutedEventArgs e)
        {
            if (!isShuffled)
            {
                label.Text = string.Empty;
                btnShuffle.Content = "洗牌中...";
                btnShuffle.IsEnabled = false;
                Shuffle();
                isShuffled = true;
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    Thread.Sleep(4200);
                    Dispatcher.BeginInvoke(() =>
                    {
                        if (timer != null)
                        {
                            timer.Stop();
                            timer = null;
                        }
                        label.Text = @"        22张大阿卡纳牌已经洗好，现在请保持注意力高度，切牌也是重要的一步，请想象你的问题，然后请开始切牌。
";
                        btnShuffle.Content = "请切牌";
                        btnShuffle.IsEnabled = true;
                    });
                }, null);
            }
            else if (!isCuted)
            {
                label.Text = string.Empty;
                btnShuffle.Content = "切牌中...";
                btnShuffle.IsEnabled = false;
                Cut();
                isCuted = true;
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    Thread.Sleep(4200);
                    Dispatcher.BeginInvoke(() =>
                    {
                        if (timer != null)
                        {
                            timer.Stop();
                            timer = null;
                        }
                        label.Text = @"        洗牌和切牌都已经顺利完成，下面进入关键性的一步——抽牌，请从22张牌中选出你的牌阵所需要的牌。

　　抽牌的时候，请摒弃杂念，不要过多犹豫，相信第一感觉。开始抽牌。";
                        btnShuffle.Content = "请选牌";
                        btnShuffle.IsEnabled = true;
                    });
                }, null);
            }
            else if (!isDrawed)
            {
                isDrawed = true;
                label.Text = string.Empty;
                //btnShuffle.Content = string.Empty;
                btnShuffle.IsEnabled = false;

                Sort();

                ThreadPool.QueueUserWorkItem((o) =>
                {
                    Thread.Sleep(2000);
                    Dispatcher.BeginInvoke(() =>
                    {
                        if (timer != null)
                        {
                            timer.Stop();
                            timer = null;
                        }

                        btnShuffle.Content = "请选择一张牌...";
                        btnShuffle.IsEnabled = false;
                    });
                }, null);
            }
            else
            {

            }
        }

        void Sort()
        {
            double topFrom = 220;
            double topUnit = 10;
            double leftFrom = -120;
            double leftUnit = 20;
            int tcount = 0;
            double rotateFrom = -66;
            double rotateUnit = 11;
            foreach (var c in canvas.Children)
            {
                TimeSpan ts = TimeSpan.FromMilliseconds(0);
                TimeSpan tsUint = TimeSpan.FromMilliseconds(1500);
                TimeSpan duration = TimeSpan.FromMilliseconds(1200);
                tcount++;

                var image = c as Image;
                if (image != null)
                {
                    image.SetValue(Canvas.ZIndexProperty, this.count - tcount);

                    var left = (double)image.GetValue(Canvas.LeftProperty);
                    var top = (double)image.GetValue(Canvas.TopProperty);

                    double topTo = topFrom - (tcount * topUnit);
                    double leftTo = leftFrom + (tcount * leftUnit);
                    double reotateTo = rotateFrom + (tcount * rotateUnit);
                    ts = ts.Add(tsUint);
                    Storyboard sb = new Storyboard();
                    //left
                    DoubleAnimationUsingKeyFrames daLeft = new DoubleAnimationUsingKeyFrames()
                    {
                        AutoReverse = false,
                        BeginTime = ts
                    };

                    EasingDoubleKeyFrame kf1 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                        Value = left,
                    };

                    EasingDoubleKeyFrame kf2 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(duration),
                        Value = leftTo,
                    };
                    daLeft.KeyFrames.Add(kf1);
                    daLeft.KeyFrames.Add(kf2);
                    Storyboard.SetTarget(daLeft, image);
                    Storyboard.SetTargetProperty(daLeft, new PropertyPath("(Canvas.Left)"));

                    //top
                    DoubleAnimationUsingKeyFrames daTop = new DoubleAnimationUsingKeyFrames()
                    {
                        AutoReverse = false,
                        BeginTime = ts
                    };

                    EasingDoubleKeyFrame kf3 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                        Value = top,
                    };

                    EasingDoubleKeyFrame kf4 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(duration),
                        Value = topTo,
                    };
                    daTop.KeyFrames.Add(kf3);
                    daTop.KeyFrames.Add(kf4);
                    Storyboard.SetTarget(daTop, image);
                    Storyboard.SetTargetProperty(daTop, new PropertyPath("(Canvas.Top)"));

                    sb.Children.Add(daLeft);
                    sb.Children.Add(daTop);
                    sb.Begin();
                }
            }
        }

        void Cut()
        {
            int count = 0;
            foreach (var c in canvas.Children)
            {
                count++;
                var image = c as Image;
                if (image != null)
                {
                    var left = (double)image.GetValue(Canvas.LeftProperty);

                    Storyboard sb = new Storyboard();
                    DoubleAnimationUsingKeyFrames daLeft = new DoubleAnimationUsingKeyFrames()
                    {
                        AutoReverse = false,
                    };

                    EasingDoubleKeyFrame kf1 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                        Value = left,
                    };

                    EasingDoubleKeyFrame kf2 = new EasingDoubleKeyFrame();
                    EasingDoubleKeyFrame kf3 = new EasingDoubleKeyFrame();
                    EasingDoubleKeyFrame kf4 = new EasingDoubleKeyFrame();
                    EasingDoubleKeyFrame kf5 = new EasingDoubleKeyFrame();
                    if (count < 7)
                    {
                        image.SetValue(Canvas.ZIndexProperty, this.count);

                        kf2.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1000));
                        kf2.Value = -40;

                        kf3.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(2000));
                        kf3.Value = -40;

                        kf4.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(3000));
                        kf4.Value = left;

                        kf5.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(4000));
                        kf5.Value = left;
                    }
                    else if (count < 14)
                    {
                        image.SetValue(Canvas.ZIndexProperty, 0);

                        kf2.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1000));
                        kf2.Value = left;

                        kf3.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(2000));
                        kf3.Value = 340;

                        kf4.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(3000));
                        kf4.Value = 340;

                        kf5.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(4000));
                        kf5.Value = left;
                    }
                    else
                    {
                        continue;
                    }

                    Storyboard.SetTarget(daLeft, image);
                    Storyboard.SetTargetProperty(daLeft, new PropertyPath("(Canvas.Left)"));
                    daLeft.KeyFrames.Add(kf1);
                    daLeft.KeyFrames.Add(kf2);
                    daLeft.KeyFrames.Add(kf3);
                    daLeft.KeyFrames.Add(kf4);
                    daLeft.KeyFrames.Add(kf5);
                    sb.Children.Add(daLeft);
                    sb.Begin();
                }
            }

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += new EventHandler(timer1_Tick);
            timer.Start();
        }

        void Shuffle()
        {
            //timer.Stop();
            //<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="tbCountInfoText">
            //    <EasingDoubleKeyFrame KeyTime="0" Value="300"/>
            //    <EasingDoubleKeyFrame KeyTime="0:0:001" Value="0"/>
            //</DoubleAnimationUsingKeyFrames>
            Random r = new Random(1000);
            int cu = 0;
            foreach (var c in canvas.Children)
            {
                if (cu++ > 10)
                    continue;

                var image = c as Image;
                if (image != null)
                {
                    var top = (double)image.GetValue(Canvas.TopProperty);
                    var left = (double)image.GetValue(Canvas.LeftProperty);

                    Storyboard sb = new Storyboard();
                    DoubleAnimationUsingKeyFrames daTop = new DoubleAnimationUsingKeyFrames()
                    {
                        AutoReverse = true,
                        RepeatBehavior = new RepeatBehavior(TimeSpan.FromMilliseconds(4000)),
                        BeginTime = TimeSpan.FromMilliseconds(r.Next(100))
                    };
                    EasingDoubleKeyFrame kf1 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                        Value = top,
                    };
                    EasingDoubleKeyFrame kf2 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(500)),
                        Value = top + (r.Next(2) == 1 ? -r.Next(60) : r.Next(60)),
                    };
                    EasingDoubleKeyFrame kf3 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1000)),
                        Value = top,
                    };
                    EasingDoubleKeyFrame kf4 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1500)),
                        Value = top + (r.Next(2) == 1 ? -r.Next(60) : r.Next(60)),
                    };
                    EasingDoubleKeyFrame kf5 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(2000)),
                        Value = top,
                    };
                    Storyboard.SetTarget(daTop, image);
                    Storyboard.SetTargetProperty(daTop, new PropertyPath("(Canvas.Top)"));
                    daTop.KeyFrames.Add(kf1);
                    daTop.KeyFrames.Add(kf2);
                    daTop.KeyFrames.Add(kf3);
                    daTop.KeyFrames.Add(kf4);
                    daTop.KeyFrames.Add(kf5);
                    sb.Children.Add(daTop);

                    DoubleAnimationUsingKeyFrames daLeft = new DoubleAnimationUsingKeyFrames()
                    {
                        AutoReverse = true,
                        RepeatBehavior = new RepeatBehavior(TimeSpan.FromMilliseconds(4000)),
                        BeginTime = TimeSpan.FromMilliseconds(r.Next(100))
                    };
                    EasingDoubleKeyFrame kf6 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)),
                        Value = left,
                    };
                    EasingDoubleKeyFrame kf7 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(500)),
                        Value = left + (r.Next(2) == 1 ? -r.Next(120) : r.Next(120)),
                    };
                    EasingDoubleKeyFrame kf8 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1000)),
                        Value = left,
                    };
                    EasingDoubleKeyFrame kf9 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1500)),
                        Value = left + (r.Next(2) == 1 ? -r.Next(120) : r.Next(120)),
                    };
                    EasingDoubleKeyFrame kf10 = new EasingDoubleKeyFrame()
                    {
                        KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(2000)),
                        Value = left,
                    };
                    Storyboard.SetTarget(daLeft, image);
                    Storyboard.SetTargetProperty(daLeft, new PropertyPath("(Canvas.Left)"));
                    daLeft.KeyFrames.Add(kf6);
                    daLeft.KeyFrames.Add(kf7);
                    daLeft.KeyFrames.Add(kf8);
                    daLeft.KeyFrames.Add(kf9);
                    daLeft.KeyFrames.Add(kf10);
                    sb.Children.Add(daLeft);
                    sb.Begin();
                }
            }

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            //throw new NotImplementedException();
        }
        int count;

        void timer_Tick(object sender, EventArgs e)
        {
            //166 56 | 120,60
            count++;
            foreach (var c in canvas.Children)
            {
                var image = c as Image;
                if (image != null)
                {
                    var top = (double)image.GetValue(Canvas.TopProperty);
                    var left = (double)image.GetValue(Canvas.LeftProperty);
                    if (top > 100 || left > 270)
                    {
                        image.SetValue(Canvas.ZIndexProperty, ++count);
                    }
                }
            }
            //throw new NotImplementedException();
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            //166 56 | 120,60
            count++;
            foreach (var c in canvas.Children)
            {
                var image = c as Image;
                if (image != null)
                {
                    var top = (double)image.GetValue(Canvas.TopProperty);
                    var left = (double)image.GetValue(Canvas.LeftProperty);
                    if (left > 320)
                    {
                        image.SetValue(Canvas.ZIndexProperty, count);
                    }
                    else if (left < 10)
                    {
                        image.SetValue(Canvas.ZIndexProperty, 0);
                    }
                }
            }
            //throw new NotImplementedException();
        }
    }
}
